package client;

import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.Socket;

import android.content.Context;
import android.widget.Toast;

public class Client_login extends Thread{
	public boolean done = false;
	public Context cn;
	public boolean first=true;
	private String path_database = "result_connection.txt";
	private String path_official;
	private String action;
	private String IP;
	private String Name;
	public int res;
	public Client_login() {
		//super();
	}
	
	public Client_login(String... param) {
		this.IP = param[0];
		this.path_official = param[1];
		this.Name = param[2];
		this.action = param[3];
	}
	
	public int login(String ip, String path_official, String name, String action) {
	    byte[] byteArray;
	    File reference = null;
	    IP = ip;
	    String answer;
	    Name = name;
	    int res = 0;
   
	    try {
	    	Socket socket = new Socket(ip, 8888);
	        if(socket.isConnected()) {
	        	System.out.println("Connexion established with the Server");
	        	DataOutputStream dOut = new DataOutputStream(socket.getOutputStream());
	        	DataInputStream dIn = new DataInputStream(socket.getInputStream());
	        	
	        	if(Integer.parseInt(action) == 1) {
	        		dOut.writeByte(1);
			        dOut.writeUTF(name);
		        	sendFile(path_official, android.os.Environment.getExternalStorageDirectory()+"/Record/"+path_official, dIn, dOut);
		        	answer = dIn.readUTF();
		        	action = "3";
		        	dOut.writeByte(3);
			        dOut.flush();
			        socket.close();
			        res = 0;
	        	} else if (Integer.parseInt(action) == 2) {
	        		dOut.writeByte(2);
			        dOut.writeUTF(name);
		        	sendFile(path_official, android.os.Environment.getExternalStorageDirectory()+"/Record/"+path_official, dIn, dOut);
		        	answer = dIn.readUTF();
		        	action = "3";
		        	if(Integer.parseInt(answer) == 1) {
		        		res = 1;
		        		System.out.println("Values res ::: "+res);
		        		System.out.println("Login win");
		        		dOut.writeByte(3);
				        dOut.flush();
				        socket.close();
		        	} else {
		        		res = 2;
		        		System.out.println("Values res ::: "+res);
		        		System.out.println("Login fail or account not found !");
		        		dOut.writeByte(3);
				        dOut.flush();
				        socket.close();
		        	}
		        	socket.close(); // MODFICIATION
	        	} else {
	        		dOut.writeByte(3);
			        dOut.flush();
	        	}
	        	/*
	        	switch(Integer.parseInt(action)) {
	        	case 1:
	        		dOut.writeByte(1);
			        dOut.writeUTF(name);
		        	sendFile(path_official, android.os.Environment.getExternalStorageDirectory()+"/Record/"+path_official, dIn, dOut);
		        	answer = dIn.readUTF();
		        	action = "3";
		        	dOut.writeByte(3);
			        dOut.flush();
	        		break;
	        	case 2:
	        		dOut.writeByte(2);
			        dOut.writeUTF(name);
		        	sendFile(path_official, android.os.Environment.getExternalStorageDirectory()+"/Record/"+path_official, dIn, dOut);
		        	answer = dIn.readUTF();
		        	if(Integer.parseInt(answer) == 1) {
		        		System.out.println("Login win");
		        	} else {
		        		System.out.println("Login fail or account not found !");
		        	}
		        	dOut.writeByte(3);
			        dOut.flush();
	        		break;
	        	case 3:
	        		dOut.writeByte(3);
			        dOut.flush();
	        		break;
	        	}*/
	        }
		    socket.close();
	    } catch (Exception e) {
	    	System.out.println("[ERROR] : "+e);
        }
		return res;
	}
  
	public void run() {
		res = login(IP, path_official, Name, action);
	}
	
	static public void sendFile2(String send, String allsend, DataInputStream input, DataOutputStream output) {
		File f = new File(send);
		String ack=null;       
	    byte [] buffer = new byte[(int)f.length()];
	    FileInputStream fis = null;
	    BufferedInputStream bis = null;

	    // Bef sending
	    try {
			output.writeUTF(send);
			ack = input.readUTF(); 
		    System.out.println("ACK : " + ack);
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}    
	    
	    
	    if (! ack.equals("ACK")) {
	    	System.out.println("Server didn't acknowledge send.  Aborted.");
	    } else {
			try {
				fis = new FileInputStream(f);
				bis = new BufferedInputStream(fis);
				try {
					bis.read(buffer,0,buffer.length);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			    try {
					output.write(buffer,0,buffer.length);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			try {
				bis.close();
				fis.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			// After sending 
			try {
				ack = input.readUTF();
				System.out.println("restulTAT ACK server : "+ack);
				if (! ack.equals("ACK")) {
					
				    System.out.println("Server failed to store the file.");
				} else {
				    System.out.println("Store successful.");
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	
	    }
	}
	
	
	static public void sendInChunks(DataInputStream input, DataOutputStream output, int togo, int chunksize) throws IOException {
		byte bytes[] = new byte[chunksize];
		int writecount;
		while (togo > 0) {
		    writecount = (togo >= chunksize ? chunksize : togo);
		    input.read(bytes, 0, writecount);
		    output.write(bytes, 0,  writecount);
		    togo = togo - writecount;
		}
		
		output.flush();
    }
    

    static private void sendFile(String send, String allsend, DataInputStream input, DataOutputStream output) {

		String ack=null;              
		System.out.println("Preparing to transfer file " + send + "...");
	
		try {
		    output.writeUTF(send);    
		    ack = input.readUTF(); 
		    System.out.println("ACK : " + ack);
		    if (! ack.equals("ACK")) {
		    	System.out.println("Server didn't acknowledge send.  Aborted.");
		    } else {
				File file = new File(allsend);
				System.out.println("FILE EXIST : "+file.exists());
				DataInputStream filestream=new DataInputStream(new FileInputStream(allsend));
				int togo = filestream.available();
				System.out.println("TOGO : "+togo);
				// push length of file to server
				output.writeInt(togo);
		
				// transfer file contents
				sendInChunks(filestream, output, togo, 1024);
				filestream.close();
		
				// is the server happy with the transfer?
				ack = input.readUTF();
				System.out.println("restulTAT ACK server : "+ack);
				if (! ack.equals("ACK")) {
					
				    System.out.println("Server failed to store the file.");
				} else {
				    System.out.println("Store successful.");
				}
		    } 
		} catch (Exception e) {
		    System.out.println("Server failed to store the file.");
		}
    }
}
